package com.adgroup.doremon_ad;

import java.io.IOException;
import java.util.ArrayList;

import model.MyApp;
import model.VideoID;
import model.film;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import util.Config;

import adapter.AdapterMyApp;
import adapter.JsonParse;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.adgroup.doremon_ad.R;


public class Menufragment extends SherlockFragment {
	ListView list;
	MenuClickInterFace mClick;
	private ProgressBar waiting;
	private View v;
	private View header;
	private View slideLike;
	private View slideView;
	private View slideSearch;
	private View slideLatest;
	private View headerMoreApp;
	

	interface MenuClickInterFace {
		void onListitemClick(String item);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mClick = (MenuClickInterFace) activity;
	}

	@SuppressWarnings("static-access")
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		list = (ListView) getView().findViewById(R.id.list);
		waiting = (ProgressBar) getView().findViewById(R.id.progressBar1);
		header = getActivity().getLayoutInflater().inflate(R.layout.title_slide_menu, null);
		slideLatest = getActivity().getLayoutInflater().inflate(R.layout.item_first_menu_latest, null);
		slideView = getActivity().getLayoutInflater().inflate(R.layout.item_first_menu_viewed, null);
		slideSearch = getActivity().getLayoutInflater().inflate(R.layout.item_first_menu_search, null);
		slideLike = getActivity().getLayoutInflater().inflate(R.layout.item_first_menu_liked, null);
		headerMoreApp = getActivity().getLayoutInflater().inflate(R.layout.title_second_slide_menu, null);
		 
		list.addHeaderView(header);  
		list.addHeaderView(slideSearch);  
		list.addHeaderView(slideLike);   
		list.addHeaderView(slideView);  
		list.addHeaderView(slideLatest);  
		list.addHeaderView(headerMoreApp);  
		
		v = getActivity().getLayoutInflater().from(getActivity()).inflate(R.layout.footer_myapp, null);
		list.addFooterView(v);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String i;
				if(arg2>=1 && arg2<=4){
					mClick.onListitemClick(arg2+"");
				}
				else
				if(arg2==myApps.size()+6){
					i = getResources().getString(R.string.urlmoreapp);
					mClick.onListitemClick(i+"");
				}
				else if(arg2!=0 && arg2!=5){
					i =((MyApp) arg0.getItemAtPosition(arg2)).getLink();
					mClick.onListitemClick(i+"");
				}
				
			}
		});
		new AsynLoadMyApp().execute();
	}
	Handler handler = new Handler();
	private ArrayList<MyApp> myApps = new ArrayList<MyApp>();
	class AsynLoadMyApp extends AsyncTask<Void, Void, String>
	{
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			waiting.setVisibility(View.VISIBLE);
		}
		@Override
		protected String doInBackground(Void... arg0) {
			return JsonParse.getInstance().getMyApp(getSherlockActivity());
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			waiting.setVisibility(View.INVISIBLE);
			try {
				if(result.equalsIgnoreCase("busy")){
					AlertDialog.Builder alert = new AlertDialog.Builder(getSherlockActivity());
					alert.setTitle("");
					alert.setMessage(getResources().getString(R.string.notresponse));
					alert.setNeutralButton(getResources().getString(R.string.notresponse_tryagain), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//mAsyncLoadCategory = new AsyncLoadCategory();
							//mAsyncLoadCategory.cancel(true);
							handler.post(new Runnable() {
								
								@Override
								public void run() {
									new AsynLoadMyApp().execute();
								}
							});
						}
					});
					alert.setPositiveButton(getResources().getString(R.string.notresponse_existapp), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							getSherlockActivity().finish();
						}
					});
					alert.show();
				}else{
					/*String[] firstMenuTitle = getResources().getStringArray(R.array.first_menu);
					int [] firstMenuImage = {R.drawable.a_action_search,R.drawable.a_rating_good,R.drawable.a_collections_view_as_grid,R.drawable.a_navigation_refresh};  
					for(int i=0;i<firstMenuImage.length;i++){
						myApps.add(new MyApp(-4+i, (-4+i)+"", firstMenuTitle[i], firstMenuImage[i]+""));
					}*/
				JSONObject json = new JSONObject(result);
				if(!json.getString("result").equalsIgnoreCase("norow")){
					JSONArray arr = json.getJSONArray("result");
					for(int i=0;i<arr.length();i++){
						JSONObject obj = arr.getJSONObject(i);
						String name = obj.getString("Name");
						String code = obj.getString("Code");
						String link = obj.getString("Link");
						int id = Integer.parseInt(obj.getString("ID"));
						MyApp cat = new MyApp(id,code, name, link);
						myApps.add(cat);
					}
					for (MyApp v : myApps) {
						if(v.getCode().equalsIgnoreCase(Config.appCat)){
							myApps.remove(v);
							break;
						}
					}
					 //int last = myApps.get(0).getID();
					//myApps.add(new MyApp(++last,"moreapp", "More Apps",getResources().getString(R.string.urlmoreapp)));
					list.setAdapter(new AdapterMyApp(getSherlockActivity(), myApps));
					
				}
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			} 
		}
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.menulist, container, false);
		return v;
	}

}
